package com.road.vast.controller;

import com.road.vast.common.entity.Result;
import com.road.vast.common.entity.ResultCode;
import com.road.vast.common.exception.CommonException;
import com.road.vast.pojo.Login;
import com.road.vast.service.LoginService;
import com.road.vast.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author 郭泽鹏
 * @Date 2020/7/30 13:44
 * @Version 1.0
 * @Description 登录授权控制器
 */
@RestController
public class LoginController {
    @Autowired
    JwtUtils jwtToken;

    @Resource
    LoginService loginService;
    /**
     * 用户登录
     * 1.根据mobile查询用户
     * 2.比较password
     * 3.生成jwt信息
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, Object> loginMap){

        String mobile = (String) loginMap.get("mobile");
        String password = (String) loginMap.get("password");

        //模拟数据
        Login login = new Login("1", "road-vast", "15323567894",
                "123456", "ABCD1234", "RV公司");

        //用户名或者密码错误
        if (login == null || !login.getPassword().equals(password)){
            return new Result(ResultCode.MOBILEORPASSWORD_ERROR);
        }else{
            //生成jwt信息
            String token = loginService.login(login, password);
            Result result = new Result(ResultCode.SUCCESS);
            result.setData(token);
            return result;
        }
    }

    /**
     * 用户登录成功后，获取用户信息
     *      1.获取用户id
     *      2.通过id查询用户
     *      3.构建返回值对象
     *      4.响应
     */
    @PostMapping("/profile")
    public Login profile(HttpServletRequest request) throws CommonException {
        //获取claims数据
        Claims claims = (Claims) request.getAttribute("user_claims");
        String userId =  claims.getId();
        String username = claims.getSubject();
        String companyId = (String) claims.get("companyId");
        String companyName = (String) claims.get("companyName");

        System.out.println("userId = " + userId + "******" + "username = " + username);
        Login login = new Login();
        login.setId(userId);
        login.setUsername(username);
        login.setCompanyId(companyId);
        login.setCompanyName(companyName);

        return login;
    }
}
